package com.wangsh.train.web.back.controller;

import java.io.IOException;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.wangsh.train.cla.pojo.AClass;
import com.wangsh.train.cla.pojo.AClassData;
import com.wangsh.train.cla.pojo.ACodeDetail;
import com.wangsh.train.cla.pojo.ACodeStat;
import com.wangsh.train.cla.service.IClassDbService;
import com.wangsh.train.cla.service.IClassOperService;
import com.wangsh.train.common.controller.BaseController;
import com.wangsh.train.common.pojo.ApiResponse;
import com.wangsh.train.common.pojo.ApiResponseEnum;
import com.wangsh.train.common.util.ConstatFinalUtil;
import com.wangsh.train.common.util.PageInfoUtil;
import com.wangsh.train.system.pojo.ASysTech;
import com.wangsh.train.system.pojo.ASysTechEnum;
import com.wangsh.train.system.service.ISystemDbService;

/**
 * 	班级后台Controller
 * 	@author wangsh
 */
@Controller
@RequestMapping("/back/class/")
public class ClassBackController extends BaseController
{
	@Resource
	private IClassDbService classDbService;
	@Resource
	private IClassOperService classOperService;
	@Resource
	private ISystemDbService systemDbService;
	
	/**
	 * 班级列表页面
	 * @return
	 */
	@RequestMapping("/classList")
	public String classList(HttpServletRequest request,Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--classList--");
		String claStatus = request.getParameter("claStatus");
		if(claStatus == null)
		{
			claStatus = "" ; 
		}
		request.setAttribute("claStatus", claStatus);
		/* 分页信息 */
		PageInfoUtil pageInfoUtil = this.proccedPageInfo(request);
		/* 搜索条件,生成公共的搜索条件 */
		Map<String, Object> condMap = this.proccedSearch(request);
		condMap.put("claStatus", claStatus);
		condMap.put("extend", "true");
		
		/* 接收参数,处理参数,放入搜索条件 */
		String orderType = request.getParameter("orderType");
		if(orderType == null)
		{
			orderType = "" ; 
		}
		request.setAttribute("orderType", orderType);
		condMap.put("orderType", orderType);
		
		/* 查询数据库
		 * 所有的数据以JSON的形式返回
		 *  */
		ApiResponse<AClass> response = this.classDbService.findCondListClassService(pageInfoUtil, condMap);
		/* 将结果存储到Request中 */
		model.addAttribute("response", response.toJSON());
		return "/back/class/classList";
	}

	/**
	 * 打开添加班级页面
	 * @return
	 */
	@RequestMapping("/classInsert")
	public String classInsert()
	{
		ConstatFinalUtil.SYS_LOGGER.info("--classInsert--");
		return "/back/class/classInsert";
	}
	
	/**
	 * 添加班级提交操作
	 * @return
	 */
	@RequestMapping(value = "/classInsertSubmit",produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String classInsertSubmit(String stTimeStr ,String edTimeStr ,String pubTimeStr , AClass clas)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--classInsertSubmit--");
		/* 保存结果 */
		ApiResponse dbResponse = new ApiResponse<Object>();
		try
		{
			clas.setStTime(this.dateFormatUtil.strDateTime(stTimeStr));
			clas.setEdTime(this.dateFormatUtil.strDateTime(edTimeStr));
			/* 为对象赋值 */
			clas.setPubTime(this.dateFormatUtil.strDateTime(pubTimeStr));
			clas.setCreateTime(new Date());
			clas.setUpdateTime(new Date());
			dbResponse = this.classDbService.saveOneClassService(clas);
			ConstatFinalUtil.SYS_LOGGER.info("--班级添加返回结果:{}--",dbResponse.toJSON());
		} catch (Exception e)
		{
			ConstatFinalUtil.SYS_LOGGER.error("添加一条记录失败了",e);
			dbResponse.setCode(ApiResponseEnum.STATUS_SERVER_ERROR.getStatus());
			Map<String, String> infoMap = new HashMap<String, String>();
			/* 报错信息的占位符 */
			infoMap.put("errinfo", e.toString());
			dbResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(dbResponse.getCode() + "") , infoMap);
		}
		return dbResponse.toJSON().toJSONString();
	}
	
	/**
	 * 打开更新班级页面
	 * @return
	 */
	@RequestMapping("/classUpdate")
	public String classUpdate(String id , String operType , Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--classUpdate--");
		/* 准备查询条件 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("id", id);
		condMap.put("extend", "true");
		/* 查询数据库 */
		ApiResponse<AClass> response = this.classDbService.findOneClassService(condMap);
		/* 存储request */
		model.addAttribute("response", response.toJSON());
		
		if("update".equalsIgnoreCase(operType))
		{
			return "/back/class/classUpdate";
		}
		return "/back/class/classInfo";
	}
	
	/**
	 * 添加班级提交操作
	 * @return
	 */
	@RequestMapping(value = "/classUpdateSubmit",produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String classUpdateSubmit(String id,HttpServletRequest request,Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--classUpdateSubmit--");
		/* 数据库操作 */
		ApiResponse<Object> dbResponse = new ApiResponse<Object>();
		try
		{
			/* 准备查询条件 */
			Map<String, Object> condMap = new HashMap<String, Object>();
			condMap.put("id", id);
			/* 查询数据库 */
			ApiResponse<AClass> response = this.classDbService.findOneClassService(condMap);
			/* 获取java对象 */
			AClass clas = response.getDataOneJava() ;
			
			/* 接收参数 */
			String regionId = request.getParameter("regionId") + "" ; 
			String cateId = request.getParameter("cateId") + "" ; 
			String name = request.getParameter("name") + "" ; 
			String address = request.getParameter("address") + "" ; 
			String stTime = request.getParameter("stTimeStr") + "" ; 
			String edTime = request.getParameter("edTimeStr") + "" ; 
			String content = request.getParameter("content") + "" ; 
			String claStatus = request.getParameter("claStatus") + "" ; 
			String status = request.getParameter("status") + "" ; 
			String pubTimeStr = request.getParameter("pubTimeStr") + "" ; 
			
			/* 设置属性 */
			clas.setName(name);
			clas.setRegionId(Integer.valueOf(regionId));
			clas.setCateId(Integer.valueOf(cateId));
			clas.setAddress(address);
			clas.setStTime(this.dateFormatUtil.strDateTime(stTime));
			clas.setEdTime(this.dateFormatUtil.strDateTime(edTime));
			clas.setClaStatus(Byte.valueOf(claStatus));
			clas.setStatus(Byte.valueOf(status));
			clas.setContent(content);
			
			clas.setPubTime(this.dateFormatUtil.strDateTime(pubTimeStr));
			clas.setUpdateTime(new Date());
			dbResponse = classDbService.updateOneClassService(clas);
			ConstatFinalUtil.SYS_LOGGER.info("--班级添加返回结果:{}--",dbResponse.toJSON());
		} catch (Exception e)
		{
			ConstatFinalUtil.SYS_LOGGER.error("更新一条记录失败了",e);
			dbResponse.setCode(ApiResponseEnum.STATUS_SERVER_ERROR.getStatus());
			Map<String, String> infoMap = new HashMap<String, String>();
			/* 报错信息的占位符 */
			infoMap.put("errinfo", e.toString());
			dbResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(dbResponse.getCode() + "") , infoMap);
		}
		return dbResponse.toJSON().toJSONString();
	}
	
	/**
	 * 代码统计列表页面
	 * @return
	 */
	@RequestMapping("/codeStatList")
	public String codeStatList(HttpServletRequest request,Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--codeStatList--");
		/* 分页信息 */
		PageInfoUtil pageInfoUtil = this.proccedPageInfo(request);
		/* 搜索条件,生成公共的搜索条件 */
		Map<String, Object> condMap = this.proccedSearch(request);
		
		String codeType = request.getParameter("codeType");
		request.setAttribute("codeType", codeType);
		
		condMap.put("codeType", codeType);
		/* 接收参数,处理参数,放入搜索条件 */
		String orderType = request.getParameter("orderType");
		if(orderType == null)
		{
			orderType = "" ; 
		}
		request.setAttribute("orderType", orderType);
		condMap.put("orderType", orderType);
		
		/* 查询数据库
		 * 所有的数据以JSON的形式返回
		 *  */
		ApiResponse<ACodeStat> response = this.classDbService.findCondListCodeStatService(pageInfoUtil, condMap);
		/* 将结果存储到Request中 */
		model.addAttribute("response", response.toJSON());
		return "/back/class/codeStatList";
	}

	/**
	 * 打开添加代码统计页面
	 * @return
	 */
	@RequestMapping("/codeStatInsert")
	public String codeStatInsert()
	{
		ConstatFinalUtil.SYS_LOGGER.info("--codeStatInsert--");
		return "/back/class/codeStatInsert";
	}
	
	/**
	 * 添加代码统计提交操作
	 * @return
	 */
	@RequestMapping(value = "/codeStatInsertSubmit",produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String codeStatInsertSubmit(String pubTimeStr , ACodeStat codeStat)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--codeStatInsertSubmit--");
		/* 保存结果 */
		ApiResponse dbResponse = new ApiResponse<Object>();
		try
		{
			/* 为对象赋值 */
			codeStat.setPubTime(this.dateFormatUtil.strDateTime(pubTimeStr));
			dbResponse = this.classDbService.saveOneCodeStatService(codeStat);
			ConstatFinalUtil.SYS_LOGGER.info("--代码统计添加返回结果:{}--",dbResponse.toJSON());
		} catch (Exception e)
		{
			ConstatFinalUtil.SYS_LOGGER.error("添加一条记录失败了",e);
			dbResponse.setCode(ApiResponseEnum.STATUS_SERVER_ERROR.getStatus());
			Map<String, String> infoMap = new HashMap<String, String>();
			/* 报错信息的占位符 */
			infoMap.put("errinfo", e.toString());
			dbResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(dbResponse.getCode() + "") , infoMap);
		}
		return dbResponse.toJSON().toJSONString();
	}
	
	/**
	 * 打开更新代码统计页面
	 * @return
	 */
	@RequestMapping("/codeStatUpdate")
	public String codeStatUpdate(String id , String operType , Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--codeStatUpdate--");
		/* 准备查询条件 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("id", id);
		/* 查询数据库 */
		ApiResponse<ACodeStat> response = this.classDbService.findOneCodeStatService(condMap);
		/* 存储request */
		model.addAttribute("response", response.toJSON());
		
		if("update".equalsIgnoreCase(operType))
		{
			return "/back/class/codeStatUpdate";
		}else if("file".equalsIgnoreCase(operType))
		{
			/* 上传文件 */
			model.addAttribute("name", "上传代码统计");
			model.addAttribute("url", "/back/class/codeStatUpdateSubmit.htm?operType=" + operType + "&id=" + id);
			return this.uploadFile;
		}
		return "/back/class/codeStatInfo";
	}
	
	/**
	 * 添加代码统计提交操作
	 * @return
	 */
	@RequestMapping(value = "/codeStatUpdateSubmit",produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String codeStatUpdateSubmit(String id,MultipartFile file,
			HttpServletRequest request,Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--codeStatUpdateSubmit--");
		/* 返回关系 */
		ApiResponse dbResponse = new ApiResponse<Object>();
		try
		{
			/* 准备查询条件 */
			Map<String, Object> condMap = new HashMap<String, Object>();
			condMap.put("id", id);
			/* 查询数据库 */
			ApiResponse<ACodeStat> response = this.classDbService.findOneCodeStatService(condMap);
			/* 获取java对象 */
			ACodeStat codeStat = response.getDataOneJava() ;
			
			Map<String, Object> paramsMap = new HashMap<String,Object>();
			boolean flag = false ; 
			String operType = request.getParameter("operType");
			if("update".equalsIgnoreCase(operType))
			{
				/* 接收参数 */
				String name = request.getParameter("name");
				String status = request.getParameter("status");
				String pubTimeStr = request.getParameter("pubTimeStr");
				String content = request.getParameter("content");
				/* 设置属性 */
				codeStat.setName(name);
				codeStat.setContent(content);
				codeStat.setStatus(Byte.valueOf(status));
				codeStat.setPubTime(this.dateFormatUtil.strDateTime(pubTimeStr));
				
				flag = true ; 
			}else if("file".equalsIgnoreCase(operType))
			{
				try
				{
					if(file != null)
					{
						ConstatFinalUtil.SYS_LOGGER.info("name:{},oriName:{}" , file.getName() , file.getOriginalFilename());
						paramsMap.put("fileName", file.getOriginalFilename());
						paramsMap.put("inputStream", file.getInputStream());
						paramsMap.put("fileSize", file.getSize());
						
						flag = true ; 
					}
				} catch (IOException e)
				{
					ConstatFinalUtil.SYS_LOGGER.error("上传文件失败了;id:{}",codeStat.getId());
				}
			}
			
			if(flag)
			{
				/* 数据库操作 */
				dbResponse = classDbService.updateOneCodeStatService(codeStat,paramsMap);
				ConstatFinalUtil.SYS_LOGGER.info("--代码统计添加返回结果:{}--",dbResponse.toJSON());
			}
		} catch (Exception e)
		{
			ConstatFinalUtil.SYS_LOGGER.error("更新一条记录失败了",e);
			dbResponse.setCode(ApiResponseEnum.STATUS_SERVER_ERROR.getStatus());
			Map<String, String> infoMap = new HashMap<String, String>();
			/* 报错信息的占位符 */
			infoMap.put("errinfo", e.toString());
			dbResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(dbResponse.getCode() + "") , infoMap);
		}
		return dbResponse.toJSON().toJSONString();
	}
	
	/**
	 * 代码统计明细列表页面
	 * @return
	 */
	@RequestMapping("/codeDetailList")
	public String codeDetailList(HttpServletRequest request,Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--codeDetailList--");
		/* 分页信息 */
		PageInfoUtil pageInfoUtil = this.proccedPageInfo(request);
		/* 搜索条件,生成公共的搜索条件 */
		Map<String, Object> condMap = this.proccedSearch(request);
		
		String codeStatId = request.getParameter("codeStatId");
		request.setAttribute("codeStatId", codeStatId);
		
		condMap.put("codeStatId", codeStatId);
		/* 查询数据库
		 * 所有的数据以JSON的形式返回
		 *  */
		ApiResponse<ACodeDetail> response = this.classDbService.findCondListCodeDetailService(pageInfoUtil, condMap);
		/* 将结果存储到Request中 */
		model.addAttribute("response", response.toJSON());
		return "/back/class/codeDetailList";
	}
	
	/**
	 * 打开更新代码统计明细页面
	 * @return
	 */
	@RequestMapping("/codeDetailUpdate")
	public String codeDetailUpdate(String id , String operType , Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--codeDetailUpdate--");
		/* 准备查询条件 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("id", id);
		/* 查询数据库 */
		ApiResponse<ACodeDetail> response = this.classDbService.findOneCodeDetailService(condMap);
		/* 存储request */
		model.addAttribute("response", response.toJSON());
		
		if("update".equalsIgnoreCase(operType))
		{
			return "/back/class/codeDetailUpdate";
		}
		return "/back/class/codeDetailInfo";
	}
	
	/**
	 * 课程资料列表页面
	 * @return
	 */
	@RequestMapping("/dataList")
	public String dataList(HttpServletRequest request,Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--dataList--");
		/* 分页信息 */
		PageInfoUtil pageInfoUtil = this.proccedPageInfo(request);
		/* 搜索条件,生成公共的搜索条件 */
		Map<String, Object> condMap = this.proccedSearch(request);
		/* 增加一个techId */
		String techId = request.getParameter("techId");
		if(techId == null)
		{
			techId = "" ; 
		}
		condMap.put("techId", techId);
		request.setAttribute("techId", techId);
		
		/* 查询数据库
		 * 所有的数据以JSON的形式返回
		 *  */
		ApiResponse<AClassData> response = this.classDbService.findCondListDataService(pageInfoUtil, condMap);
		/* 将结果存储到Request中 */
		model.addAttribute("response", response.toJSON());
		
		/* 查询所有启用的课程资料 */
		condMap.clear();
		condMap.put("status", ASysTechEnum.STATUS_ENABLE.getStatus());
		ApiResponse<ASysTech> sysTechResponse = this.systemDbService.findCondListSysTechService(null,condMap);
		request.setAttribute("sysTechResponse", sysTechResponse.toJSON());
		return "/back/class/dataList";
	}

	/**
	 * 打开添加课程资料页面
	 * @return
	 */
	@RequestMapping("/dataInsert")
	public String dataInsert(HttpServletRequest request)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--dataInsert--");
		/* 查询所有的技术 */
		Map<String, Object> condMap = this.proccedSearch(request);
		/* 查询所有启用的课程资料 */
		condMap.clear();
		condMap.put("status", ASysTechEnum.STATUS_ENABLE.getStatus());
		ApiResponse<ASysTech> sysTechResponse = this.systemDbService.findCondListSysTechService(null,condMap);
		request.setAttribute("sysTechResponse", sysTechResponse.toJSON());
		return "/back/class/dataInsert";
	}
	
	/**
	 * 添加课程资料提交操作
	 * @return
	 */
	@RequestMapping(value = "/dataInsertSubmit",produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String dataInsertSubmit(String pubTimeStr , AClassData data)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--dataInsertSubmit--");
		/* 为对象赋值 */
		data.setPubTime(this.dateFormatUtil.strDateTime(pubTimeStr));
		data.setCreateTime(new Date());
		data.setUpdateTime(new Date());
		/* 保存结果 */
		ApiResponse response = this.classDbService.saveOneDataService(data);
		ConstatFinalUtil.SYS_LOGGER.info("--课程资料添加返回结果:{}--",response.toJSON());
		return response.toJSON().toJSONString();
	}
	
	/**
	 * 打开更新课程资料页面
	 * @return
	 */
	@RequestMapping("/dataUpdate")
	public String dataUpdate(String id , String operType , Model model,HttpServletRequest request)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--dataUpdate--");
		/* 准备查询条件 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("id", id);
		/* 查询数据库 */
		ApiResponse<AClassData> response = this.classDbService.findOneDataService(condMap);
		/* 存储request */
		model.addAttribute("response", response.toJSON());
		
		if("update".equalsIgnoreCase(operType))
		{
			/* 查询所有启用的课程资料 */
			condMap.clear();
			condMap.put("status", ASysTechEnum.STATUS_ENABLE.getStatus());
			ApiResponse<ASysTech> sysTechResponse = this.systemDbService.findCondListSysTechService(null,condMap);
			request.setAttribute("sysTechResponse", sysTechResponse.toJSON());
			return "/back/class/dataUpdate";
		}
		return "/back/class/dataInfo";
	}
	
	/**
	 * 添加课程资料提交操作
	 * @return
	 */
	@RequestMapping(value = "/dataUpdateSubmit",produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String dataUpdateSubmit(String id,
			HttpServletRequest request,Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--dataUpdateSubmit--");
		ApiResponse<Object> dbRes = new ApiResponse<Object>();
		/* 准备查询条件 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("id", id);
		/* 查询数据库 */
		ApiResponse<AClassData> response = this.classDbService.findOneDataService(condMap);
		/* 获取java对象 */
		AClassData data = response.getDataOneJava() ;
		
		boolean flag = false ; 
		String operType = request.getParameter("operType");
		if("update".equalsIgnoreCase(operType))
		{
			/* 接收参数 */
			String techId = request.getParameter("techId");
			String name = request.getParameter("name");
			String videoPath = request.getParameter("videoPath");
			String videoCode = request.getParameter("videoCode");
			String status = request.getParameter("status");
			String timeLong = request.getParameter("timeLong");
			String pubTimeStr = request.getParameter("pubTimeStr");
			String content = request.getParameter("content");
			/* 设置属性 */
			data.setTechId(Integer.valueOf(techId));
			data.setName(name);
			data.setVideoPath(videoPath);
			data.setVideoCode(videoCode);
			data.setContent(content);
			data.setStatus(Byte.valueOf(status));
			data.setTimeLong(Integer.valueOf(timeLong));
			
			data.setPubTime(this.dateFormatUtil.strDateTime(pubTimeStr));
			
			flag = true; 
		}
		
		if(flag)
		{
			/* 数据库操作 */
			dbRes = classDbService.updateOneDataService(data);
			ConstatFinalUtil.SYS_LOGGER.info("--课程资料添加返回结果:{}--",dbRes.toJSON());
		}
		return dbRes.toJSON().toJSONString();
	}
	
	/**
	 * 课程资料批量操作
	 * @return
	 */
	@RequestMapping(value = "/dataBatch" , produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String dataBatch(HttpServletRequest request,Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--dataBatch--");
		Map<String, Object> condMap = new HashMap<String, Object>();
		ApiResponse<Object> apiResponse = new ApiResponse<Object>();
		/* 从session中获取信息 */
		String[] ids = request.getParameterValues("ids");
		
		/* 操作类型 */
		String operType = request.getParameter("operType");
		if(ids != null)
		{
			int totalNum = ids.length ; 
			int succedNum = 0 ; 
			int failedNum = 0 ; 
			for (int i = 0; i < ids.length; i++)
			{
				String id = ids[i];
				if("updateStatus".equalsIgnoreCase(operType))
				{
					String status = request.getParameter("status");
					
					condMap.clear();
					condMap.put("id", id);
					ApiResponse<AClassData> apiResponseDb = this.classDbService.findOneDataService(condMap);
					AClassData data = apiResponseDb.getDataOneJava();
					/* 设置状态 */
					data.setStatus(Byte.valueOf(status));
					data.setPubTime(new Date());
					
					ApiResponse<Object> dataClassResponse = this.classDbService.updateOneDataService(data);
					if(dataClassResponse.getCode() == ApiResponseEnum.STATUS_SUCCESS.getStatus())
					{
						succedNum ++ ; 
					}else
					{
						failedNum ++ ; 
					}
				}
			}
			
			StringBuffer sb = new StringBuffer();
			sb.append("总条数:" + totalNum + ";");
			sb.append("成功条数:" + succedNum + ";");
			sb.append("失败条数:" + failedNum + ";");
			apiResponse.setCode(ApiResponseEnum.STATUS_SUCCESS.getStatus());
			apiResponse.setInfo(sb.toString(), Collections.EMPTY_MAP);
		}
		return apiResponse.toJSON().toJSONString();
	}
}
